
Swift 模型化使用SQLite3
本文介绍如何在 Swift 中通过模型化方式使用 SQLite3 数据库,实现对 SQLite.Swift 库的封装,让数据库操作更加便捷。
在iOS中,使用未经处理的SQLite库是一件很痛苦的事情,所以出现了很多封装后的库,其中在Swift语言中使用的较为广泛的库是SQLite.Swift。使用过的都知道,这个库很好,但是不支持模型化转换就很苦恼,正因为如此,本文所写的也正是对SQLite.Swift的模型化封装
使用
- 创建的模型实现
SQLiteProtocol协议即可
1import SQLiteManager
2
3class TestModel: NSObject, SQLiteProtocol {}
4struct TestModel: SQLiteProtocol {}
- 创建模型后即可快速开始数据库操作
1/// 插入模型(默认不存在会创建
2SQLiteManager.default.insert(testModel)
3
4/// 删除模型
5SQLiteManager.default.delete(testModel)
6
7/// 更新模型数据
8testModel.name = "Ree"
9testModel.create_time = Int(Date().timeIntervalSince1970)
10SQLiteManager.default.update(testModel)
11
12/// 查询模型数据
13let arr = SQLiteManager.default.select(TestModel.tableName)
14let models = arr.map({ TestModel.deserialize(from: $0) })
15print("查询到数据: \(models)")
16
17/// 删除数据表
18SQLiteManager.default.drop(TestModel.tableName)
以下是实现原理,若想直接使用,请直接访问Github,或者直接pod安装
1 pod 'JXSQLiteManager'
基础协议
首先我们需要准备一个通用的协议来规定一些通用的属性,以及转模型时需要的初始化方法。后续所有的模型都是实现该协议来实现
1public protocol SQLiteProtocol {
2 static var tableName: String { get }
3 /// 主键字段
4 var primaryKey: String? { get }
5 /// 忽略的字段,不保存
6 var ignoreKeys: [String]? { get }
7 /// 唯一的字段
8 var uniqueKeys: [String]? { get }
9
10 init(_ dict: [String: Any])
11}
声明属性模型
有了基础协议后,我们还需要一个模型来保存反射解析出的属性列表来记录当前模型有哪些数据表属性
1
2public struct SQLitePropModel {
3 public var key: String
4 public var value: Any
5 /// 是否是主键
6 public var primary = false
7
8 private var option = false
9}
通过反射获取每一列的属性,可选类型(optional)在数据表中即为非必填项,并且当属性值为nil时记录值为空
1 public init(_ key: String, value: Any, primary: Bool) {
2 self.key = key
3 self.primary = primary
4
5 let mirror = Mirror(reflecting: value)
6 self.option = mirror.displayStyle == .optional
7 // unwrap optional
8 if mirror.displayStyle != .optional {
9 self.value = value
10 }else if mirror.children.count == 0 { self.value = "" }
11 else {
12 let (_, some) = mirror.children.first!
13 self.value = some
14 }
15 }
支持的数据类型对应数据库类型如下
1 public var datatype: String {
2 let nativeType = type(of: value)
3 var datatype = ""
4
5 if nativeType is Int.Type || nativeType is Int?.Type {
6 datatype = "INTEGER"
7 }else if nativeType is Float.Type || nativeType is Double.Type || nativeType is Float?.Type || nativeType is Double?.Type {
8 datatype = "REAL"
9 }else if nativeType is NSString.Type || nativeType is String.Type || nativeType is Character.Type || nativeType is NSString?.Type || nativeType is String?.Type || nativeType is Character?.Type {
10 datatype = "TEXT"
11 }else if nativeType is Bool.Type || nativeType is Bool?.Type {
12 datatype = "REAL"
13 }else{
14 assert(true, "sqlType:不支持的类型")
15 }
16 return datatype
17 }
获取模型属性
通过数据模型反射出对应的数据表属性模型列表,在该方法中处理需要忽略的模型字段以及模型属性列表
1/// 反射保存属性的model
2public struct SQLMirrorModel {
3 public static func operateByMirror(object: SQLiteProtocol) -> SQLMirrorModel {
4 let mirror = Mirror(reflecting: object)
5 var props = [SQLitePropModel]()
6 for case let (key?, value) in mirror.children {
7 let model = SQLitePropModel(key, value: value, primary: object.primaryKey == key)
8 if object.ignoreKeys?.contains(key) == true {
9 continue
10 }
11 props.append(model)
12 }
13
14 if mirror.displayStyle != .class || mirror.displayStyle != .struct {
15 assert(true, "operateByMirror:不支持的类型")
16 }
17 return SQLMirrorModel(type(of: object).tableName, props: props, primaryKey: object.primaryKey)
18 }
19}
多有不足,敬请指教👻
- 标题: Swift 模型化使用SQLite3
- 作者: Jerome Xiong
- 创建于: 2020-04-29 19:33:57
- 链接: https://jeromexiong.github.io/2020/04/29/iOS-Swift/Swift 模型化使用SQLite3/
- 版权声明:本文章采用 CC BY-NC-SA 4.0 进行许可。
评论